import { defineStore } from 'pinia'
import { store } from '@/stores'
import { type RouteRecordRaw } from 'vue-router'
// import { routerGenerator, asyncImportRoute } from '@/router/generator-routers'
// import { ResultEnum } from '@/enums/httpEnum'
import {
  routerGenerator,
  handleRouterResponse
} from '@/router/generator-routers'

export interface IAsyncRouteState {
  routesList: any[]
  isColumnsMenuHover: boolean
  isColumnsNavHover: boolean
  keepAliveComponents: string[]
  isDynamicAddedRoute: boolean
}

export const useAsyncRouteStore = defineStore('routers', {
  state: (): IAsyncRouteState => ({
    routesList: [],
    isColumnsMenuHover: false,
    isColumnsNavHover: false,
    keepAliveComponents: [],
    isDynamicAddedRoute: false
  }),
  getters: {
    getIsDynamicAddedRoute(): boolean {
      return this.isDynamicAddedRoute
    }
  },
  actions: {
    async setDynamicAddedRoute(added: boolean) {
      this.isDynamicAddedRoute = added
    },
    async setRoutesList(data: any) {
      this.routesList = data
    },
    async setColumnsMenuHover(bool: boolean) {
      this.isColumnsMenuHover = bool
    },
    async setColumnsNavHover(bool: boolean) {
      this.isColumnsNavHover = bool
    },
    async setKeepAliveComponents(compNames: any) {
      // 设置需要缓存的组件
      this.keepAliveComponents = compNames
    },
    async generateRoutes() {
      let routes: RouteRecordRaw[] = []
      // 动态获取菜单
      try {
        routes = await generatorDynamicRouter()
      } catch (error) {
        console.log(error)
      }
      const list = await routerGenerator(routes)
      if (list) {
        this.setDynamicAddedRoute(true)
      }
      // console.log('获取路由数据....')
      // console.log(list)
      // if (routes == null || routes == undefined || routes.length == 0)
      //   return null
      // this.setRoutesList(list)
      return list
    }
  }
})

/**
 * 动态生成菜单
 * @returns {Promise<Router>}
 */
async function generatorDynamicRouter(): Promise<RouteRecordRaw[]> {
  return new Promise((resolve, reject) => {
    const dat = ['/home', '/system/menu']
    // 测试获取菜单
    const routeList = handleRouterResponse(dat)
    if (routeList) {
      resolve(routeList)
    } else {
      reject(null)
    }

    // adminMenus()
    //   .then(response => {
    //     // console.log(response)
    //     const { data, status } = response
    //     if (status === ResultEnum.SUCCESS) {
    //       const routeList = routerGenerator(data)
    //       asyncImportRoute(routeList)
    //       resolve(routeList)
    //     } else {
    //       reject(null)
    //     }
    //   })
    //   .catch(() => {
    //     reject(null)
    //   })
  })
}

// Need to be used outside the setup
export function useAsyncRouteStoreWidthOut() {
  return useAsyncRouteStore(store)
}
